<template>
  <div id="orgManageDiv">
    <Breadcrumb content="机构管理" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="35">
          <vxe-toolbar perfect ref="toolbarRef">
            <template #buttons>
              <div class="smallToolTitle">组织机构</div>
              <vxe-input style="width: 130px" v-model="orgForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findOrgList" @keyup="keyupEnter" @search-click="handleSearch(orgForm.searchValue)"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findOrgList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addOrg('', '')"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :loading="saveLoading" @click="saveOrg"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="同步数据" @click="pullOrg"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="orgTable" class="mytable-scrollbar" border="inner" height="auto" :data="orgaList" :loading="showLoading" :expand-config="{ expandAll: true, reserve: true }" @current-change="orgRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }" :tree-config="{
                expandAll: true,
                transform: true,
                rowField: 'id',
                parentField: 'parentId'
              }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source :reserve="true">
              <vxe-column field="code" title="编码" width="170" tree-node :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input type="text" :underline="false" v-model="row.code"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="id" title="组织机构Id" width="200" ></vxe-column>
              <vxe-column field="name" title="名称" min-width="110" :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input type="text" :underline="false" v-model="row.name"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column title="操作" width="90" align="center" fixed="right">
                <template #default="{ row }">
                  <el-tooltip class="item" effect="dark" content="新建子分组" placement="left">
                    <vxe-button type="text" status="primary" icon="vxe-icon-square-plus" circle @click="addOrg(row.id, row)"></vxe-button>
                  </el-tooltip>
                  <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="deleteOrg(row)"></vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <!-- 右侧表单 -->
        <Pane size="65">
          <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
            <el-tab-pane label="基础数据复制" name="first" :disabled="isEmpty(sltOrgManage.id)">
              <!-- <SysModuleAndMenuByOrg ref="moduleAndMenuByOrgRef" /> -->
              <div v-if="curLoginUser.username === 'admin'">
                <vxe-toolbar>
                  <template #buttons>
                    <vxe-button type="text" class="button-blue" :loading="saveLoadingCopy" content="全选" @click="selectAll"></vxe-button>
                    <vxe-button type="text" class="button-blue" :loading="saveLoadingCopy" content="取消全选" @click="cancelSelect"></vxe-button>
                  </template>
                </vxe-toolbar>

                <vxe-checkbox-group v-model="valGroup1">
                  <vxe-checkbox :label="itm.label" :content="itm.content" v-for="(itm, idx) in checkBoxList" :key="idx"></vxe-checkbox>
                </vxe-checkbox-group>

                <vxe-toolbar>
                  <template #buttons>
                    <span class="margin-lr-xs">从来源机构</span>
                    <VxePulldownSelectionWithNa style="width: 40%" :url="'/api/sys/findOrganizationList'" @confirmClick="SelectRowClick" :tableColumn="[
                        { type: 'seq', title: '#', width: '20px' },
                        { field: 'name', title: '名称' },
                        { field: 'code', title: '仪器编码' }
                      ]" :aimKeys="[
                        { aimKey: 'sourceOrgId', rowKey: 'id' },
                        { aimKey: 'sourceOrgName', rowKey: 'name' }
                      ]" :displayTexts="['name']" :displayTextObj="sourceOrgObj.sourceOrgName ? sourceOrgObj.sourceOrgName : ''" />
                    <span class="margin-lr-sm">复制到</span>
                    <span class="vxe-icon-arrow-double-right"></span>
                    <span class="margin-lr-sm text-bold text-blue">{{ curSelectRow.name }}</span>
                  </template>
                </vxe-toolbar>
                <vxe-toolbar>
                  <template #buttons>
                    <span class="vxe-icon-warning-triangle-fill margin-right-sm text-bold text-blue"></span>
                    <span class="text-blue">复制后会自动创建管理员账号,登录账号名称 组织机构名称首字母后加admin,默认登录密码:123456</span>
                  </template>
                </vxe-toolbar>
                <vxe-toolbar>
                  <template #buttons>
                    <vxe-button type="text" class="button-blue" :loading="saveLoadingCopy" content="开始复制" @click="startCopy"></vxe-button>
                  </template>
                </vxe-toolbar>
              </div>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { AppStore } from '../../stores/store';
import { isEmpty } from 'lodash';
import SysModuleAndMenuByOrg from './SysModuleAndMenuByOrg.vue'; //失控记录图表
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';
import { IsEmpty } from '@/utils/common';

// 全局变量定义区 ==========
let store = AppStore();
let showLoading = ref(false); //刷新加载状态
let saveLoading = ref(false); //保存加载状态
let sltOrgManage: any = ref({});
let valGroup1 = ref(['Module', 'Role', 'SysOption', 'Dictionary', 'Interface', 'Rules', 'Report', 'CreateUser', 'mainInfoConfig', 'bacInfoConfig', 'labNodeSetting']);
let checkBoxList = reactive([
  { id: '1', label: 'Module', content: '功能模块' },
  { id: '2', label: 'Role', content: '角色管理' },
  { id: '3', label: 'SysOption', content: '系统选项' },
  { id: '4', label: 'Dictionary', content: '系统字段' },
  { id: '5', label: 'Interface', content: '接口平台' },
  { id: '6', label: 'Rules', content: '编号规则设置' },
  { id: '7', label: 'Report', content: '报表模板库' },
  { id: '8', label: 'CreateUser', content: '创建管理员用户' },
  { id: '9', label: 'mainInfoConfig', content: '检验报告模板设置' },
  { id: '10', label: 'bacInfoConfig', content: '微生物模板设置' },
  { id: '11', label: 'labNodeSetting', content: '标本流转节点' }
]); /**待复制模块 */
let sourceOrgObj = reactive({ sourceOrgId: '', sourceOrgName: '' });
// 机构根据关键字查询
let orgForm = {
  id: '',
  parentId: null,
  parentName: '',
  name: '',
  code: '',
  tenantId: null,
  //用户输入查询内容
  searchValue: ''
};
let orgTable = ref(null); //机构表格ref
let orgaList: any = reactive([]); //机构列表数据
let curSelectRow = reactive({});
let curLoginUser = reactive({}); //
let saveLoadingCopy = ref(false);
// 方法定义区 =============
// 页面加载时更新组织机构列表(左侧)
onMounted(() => {
  let user = localStorage.getItem('userInfo');
  let userObj = JSON.parse(user);
  Object.assign(curLoginUser, userObj);
  findOrgList();
});

// 获取机构列表(默认获得全部)
function findOrgList() {
  showLoading.value = true;
  const $table = proxy.$refs.orgTable;
  if ($table) {
    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);
  }
  const url = '/api/sys/findOrganizationPageList';
  orgaList.length = 0; //放入数据前清空数据
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { pageIndex: 1, pageSize: 50 } })
    .then((res: any) => {
      orgaList.push(...res.data.records);
      orgRowClick({ row: orgaList[0] }); //默认选中第一条数据
      $table.setAllTreeExpand(true);
      // $table.loadData(orgaList,true);
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      // VxeMessage('获取机构列表失败',VxeNotifyType.error)
    });
}
let activeName = ref('first');
let moduleAndMenuByOrgRef: any = ref(null);

// 点击机构当前行触发的事件
function orgRowClick({ row }: any) {
  if (isEmpty(row)) {
    sltOrgManage.value = {};
  } else {
    Object.assign(curSelectRow, row);
    (proxy.$refs.orgTable as any).setCurrentRow(row);
    sltOrgManage.value = row;
    if (activeName.value == 'first') {
      const iindex = orgaList.findIndex((item) => item.id == sltOrgManage.value.id);

      moduleAndMenuByOrgRef.value.initPage(sltOrgManage.value, iindex);
    }
  }
}
function tabHandleClick(tab) {
  const iindex = orgaList.findIndex((item) => item.id == sltOrgManage.value.id);

  if (tab.props.name == 'first') {
    moduleAndMenuByOrgRef.value.initPage(sltOrgManage.value, iindex);
  }
}

// 查询/刷新
function handleSearch(row: string | number) {
  const $table = orgTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);
  }
  const url = '/api/sys/findOrganizationPageList';
  orgaList.length = 0;
  proxy.$http
    .get(url, { params: { keywords: row, pageIndex: 1, pageSize: 50 } })
    .then((res: any) => {
      orgaList.push(...res.data.records);
      orgRowClick({ row: orgaList[0] }); //默认选中第一条数据
      $table.setAllRowExpand(true);
      $table.setAllTreeExpand(true);
      // $table.loadData(orgaList, true);
    })
    .catch((err: any) => {
      // VxeMessage('查询刷新失败', VxeNotifyType.error);
    });
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(orgForm.searchValue);
  }
}
// 新建一级机构/子结构
async function addOrg(parentids: any, row: any): Promise<void> {
  //clearForm();
  const $table = orgTable.value;
  if ($table) {
    // 获取新增的数据记录
    const record = {
      code: '',
      name: '',
      parentId: parentids != '' || parentids != null ? parentids : null,
      id: ''
    };
    // orgaList.push(record);
    // $table.loadData(orgaList);
    const { row: newRow } = await $table.insertAt(record, -1);
    await $table.setEditRow(record);
    if (row) {
      await $table.setTreeExpand(row, true); // 新建一行空数据时展开这一栏
    }
  }
}

// 保存
async function saveOrg() {
  saveLoading.value = true;
  const $table = proxy.$refs.orgTable;
  if ($table) {
    const updateRecords = await $table.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });

    const InsertRecords = await $table.getInsertRecords().filter((m: any) => {
      return m.id === '';
    });

    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);

    // 修改机构
    updateRecords.forEach((e: any) => {
      const url = '/api/sys/editOrg';
      const tOrganization = e;
      proxy.$http
        .post(url, tOrganization)
        .then((res: any) => {
          $table.setAllTreeExpand(true);
          VxeMessage('修改机构成功', VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage('修改机构失败', VxeNotifyType.error);
        });
    });

    // 新增机构
    InsertRecords.forEach((ele: any) => {
      const url = '/api/sys/addOrg';
      const tOrganization = ele;
      proxy.$http
        .post(url, tOrganization)
        .then((res: any) => {
          $table.setAllTreeExpand(true);
          VxeMessage('新增机构成功', VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage('新增机构失败', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      saveLoading.value = false;
    }, 500);
    findOrgList();
  }
}

// 删除机构
function deleteOrg(row: any) {
  const $table = orgTable.value;
  $table.setAllTreeExpand(true);
  $table.setAllRowExpand(true);
  proxy
    .$confirm('确定删除此组织机构？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/sys/deleteOrgOrDept/' + row.id;
      if (row.id) {
        proxy.$http.delete(url).then((res: any) => {
          if (res.status.code === 400) {
            VxeMessage('该机构下存在机构信息，不能删除', VxeNotifyType.error);
          } else {
            VxeMessage('删除机构成功', VxeNotifyType.success);
          }
          findOrgList();
          $table.setAllTreeExpand(true);
        });
      } else {
        if ($table) {
          await $table.remove(row);
          VxeMessage('删除机构成功', VxeNotifyType.success);
        }
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
// 同步数据
function pullOrg() { }

/**下拉选中行事件 */
function SelectRowClick(e) {
  sourceOrgObj.sourceOrgId = e.row['id'];
  sourceOrgObj.sourceOrgName = e.row['name'];
}
/**开始复制 */
async function startCopy() {
  if (!valGroup1.value || valGroup1.value.length <= 0) {
    VxeMessage('请选需要复制的模块', VxeNotifyType.warning);
    return;
  }
  if (IsEmpty(sourceOrgObj.sourceOrgId)) {
    VxeMessage('请选择来源组织机构', VxeNotifyType.warning);
    return;
  }
  const type = await VXETable.modal.confirm(`复制会删除[${curSelectRow.name}]组织机构已有的数据,确定复制选中的${valGroup1.value.length}项模块的数据?`); /*不能改el  $confirm 回车事件冒泡你*/
  if (type === 'confirm') {
    const iindex = orgaList.findIndex((item) => item.id == sltOrgManage.value.id);

    saveLoadingCopy.value = true;
    const moduleAddParam = {
      sourceOrgId: sourceOrgObj.sourceOrgId,
      goalOrgId: curSelectRow.id,
      orgIndex: iindex,
      moduleList: valGroup1.value
    };
    proxy.$http
      .post('/api/pubReport/copyBaseData', moduleAddParam)
      .then((res: any) => {
        if (res.status.code === 1) {
          VxeMessage('复制成功', VxeNotifyType.success);
        }
        saveLoadingCopy.value = false;
      })
      .catch((err: any) => {
        saveLoadingCopy.value = false;
        VxeMessage('复制异常', VxeNotifyType.error);
      });
  }
}
/**全选 */
function selectAll(val: any) {
  valGroup1.value.length = 0;
  for (let i = 0; i < checkBoxList.length; i++) {
    valGroup1.value.push(checkBoxList[i].label);
  }
}
/**取消全选 */
function cancelSelect() {
  valGroup1.value.length = 0;
}
</script>

<style lang="scss" scoped>
#orgManageDiv {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }

    // 机构表格
    :deep(.vxe-table--render-default) {
      height: 100%;
    }
    :deep(.vxe-table--render-wrapper) {
      height: 100%;
      background-color: $base-white;
    }
    .tableBox {
      height: calc(100% - 39px);
    }
  }
}
</style>
